package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.DeviceDetailMapper;
import com.indusfo.spc.mapper.DeviceMapper;
import com.indusfo.spc.pojo.Classe;
import com.indusfo.spc.pojo.DeviceDetail;
import com.indusfo.spc.service.DeviceDetailService;
import com.indusfo.spc.untlis.DateUtils;
import com.indusfo.spc.vo.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class DeviceDetailServiceImpl implements DeviceDetailService {

    private  static  final Logger logger = LoggerFactory.getLogger(DeviceDetailServiceImpl.class);

    @Resource
    private DeviceDetailMapper deviceDetailMapper;

    /**
     * 查询
     * @param deviceDetail
     * @return
     */
    @Override
    public JSONObject queryDeviceDetail(DeviceDetail deviceDetail) {
        List<DeviceDetail> listDeviceDetail = null;
        try{
            Integer pagesize = deviceDetail.getPagesize();
            Integer pageindex = deviceDetail.getPageindex();
            if(pagesize != null && pageindex != null) {
                deviceDetail.setIncept(pagesize*(pageindex - 1));
            }
            listDeviceDetail = deviceDetailMapper.listDeviceDetail(deviceDetail);
            //判断查询出来的集合是否为空
            if(listDeviceDetail.isEmpty()) {
                return JSONObject.oK("没有设备明细相关数据", listDeviceDetail, 0);
            }
            //用来记录查询出来的条数
            int count = deviceDetailMapper.countDeviceDetail(deviceDetail);
            return JSONObject.oK("查询成功", listDeviceDetail, count);
        }catch(
                GlobalException e){//捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    /**
     * 删除 停用 启用
     * @param deviceDetailIds
     * @param dataState
     * @return
     */
    @Override
    public JSONObject definedDeviceDetail(Long[] deviceDetailIds, Integer dataState) {
        try{
            //判断传入的参数是否为null
            if(dataState == null) {
                //为null抛出异常
                throw new ParamsErrorException("数据状态不能为空");
            }else if(dataState != 1 && dataState != 2 && dataState != 3) {
                throw new ParamsErrorException("数据状态错误");
            }
            if(deviceDetailIds == null || deviceDetailIds.length == 0) {
                throw new ParamsErrorException("请选择设备明细");
            }
            //调用删除的接口
            int row = deviceDetailMapper.definedDeviceDetail(deviceDetailIds,dataState);
            //声明msg字符串，用来存抛出的异常
            String msg = "";
            if (row == 0) {
                // 判断传入的数据状态参数dataState,返回相应信息
                switch (dataState) {
                    case 1:
                        throw new ModifyFailedException("启用失败");
                    case 2:
                        throw new ModifyFailedException("删除失败");
                    case 3:
                        throw new ModifyFailedException("停用失败");
                    default:
                        break;
                }
            } else {
                switch (dataState) {
                    case 1:
                        msg = "启用成功";break;
                    case 2:
                        msg = "删除成功";break;
                    case 3:
                        msg = "停用成功";break;
                    default:
                        break;
                }
            }
            return JSONObject.oK(msg);
        }catch(
        GlobalException e){//捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    /**
     * 新增
     * @param deviceDetail
     * @return
     */
    @Override
    public JSONObject insertDeviceDetail(DeviceDetail deviceDetail) {
        try{
            //判断传入的参数是否为null
            if(deviceDetail.getDeviceDetailId()!=null) {
                //为null则抛出异常
                throw new ParamsErrorException("新增设备明细时不能有id");
            }
            if(deviceDetail.getRemark()==null){
                deviceDetail.setRemark("");
            }
            checkParam(deviceDetail);
            String checkConflictResult = checkConflict(deviceDetail);
            if(!com.indusfo.spc.untlis.StringUtils.isEmpty(checkConflictResult)){
                return JSONObject.build(JSONObject.ERROR,checkConflictResult);
            }
            int row = deviceDetailMapper.insertSelective(deviceDetail);
            if(row == 0) {
                throw new ModifyFailedException("新增设备明细失败");
            }
            return JSONObject.oK("新增成功");
        }catch(
                GlobalException e){//捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    /**
     * 编辑
     * @param deviceDetail
     * @return
     */
    @Override
    public JSONObject updateDeviceDetail(DeviceDetail deviceDetail) {
        try {
            //判断传入的参数是否为null
            if(deviceDetail.getDeviceDetailId()==null) {
                //为null则抛出异常
                throw new ParamsErrorException("修改设备明细id不能为空");
            }
            checkParam(deviceDetail);
            String checkConflictResult = checkConflict(deviceDetail);
            if(!com.indusfo.spc.untlis.StringUtils.isEmpty(checkConflictResult)){
                return JSONObject.build(JSONObject.ERROR,checkConflictResult);
            }
            //调用修改的接口
            int row = deviceDetailMapper.updateByPrimaryKeySelective(deviceDetail);
            if(row == 0) {
                throw new ModifyFailedException("编辑失败");
            }
            return JSONObject.oK("编辑成功");
        }catch (GlobalException e) {//捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    /**
     * 校验参数
     * @param deviceDetail
     */
    public void checkParam(DeviceDetail deviceDetail){
        if(deviceDetail.getDeviceId()==null){
            throw new ParamsErrorException("请选择设备");
        }
        if(StringUtils.isEmpty(deviceDetail.getEviceDetailName())){
            throw new ParamsErrorException("设备明细名称不能为空");
        }
        if(deviceDetail.getEviceDetailName().length()>50){
            throw new ParamsErrorException("设备明细名称长度不能大于50");
        }
        if(!org.apache.commons.lang3.StringUtils.isEmpty(deviceDetail.getStartDate())){
            try {
                Date parse = new SimpleDateFormat("HH:mm:ss").parse(deviceDetail.getStartDate());
            } catch (ParseException e) {
                throw new ParamsErrorException("开始时间格式错误");
            }
        }
        if(!org.apache.commons.lang3.StringUtils.isEmpty(deviceDetail.getEndDate())){
            try {
                Date parse = new SimpleDateFormat("HH:mm:ss").parse(deviceDetail.getEndDate());
            } catch (ParseException e) {
                throw new ParamsErrorException("结束时间格式错误");
            }
        }
        // 名称不能重复
        Integer NameCounts = deviceDetailMapper.queryDeviceDetailName(deviceDetail);
        if (NameCounts !=0) {
            throw new ParamsErrorException("该设备明细名称已存在");
        }
    }

    /**
     *
     */
    public String checkConflict(DeviceDetail deviceDetail){
        //判断当前与新增/修改是否发生冲突
        List<DeviceDetail> deviceDetailList= deviceDetailMapper.queryListByDevice(deviceDetail);
        for (DeviceDetail detail : deviceDetailList) {
            int startDateCompare1 = DateUtils.compareDate(detail.getStartDate(), deviceDetail.getStartDate());
            int startDateCompare2 = DateUtils.compareDate(detail.getEndDate(), deviceDetail.getStartDate());
            int endDateCompare1 = DateUtils.compareDate(detail.getStartDate(), deviceDetail.getEndDate());
            int endDateCompare2 = DateUtils.compareDate(detail.getEndDate(), deviceDetail.getEndDate());
            if((startDateCompare1<=0 && startDateCompare2>0 && endDateCompare1<0  && endDateCompare2>=0) ||
                    (startDateCompare1>0 && startDateCompare2>0 && endDateCompare1<0 && endDateCompare2>=0) ||
                    (startDateCompare1<0 && startDateCompare2>0 && endDateCompare1<0 && endDateCompare2<0) ||
                    (startDateCompare1>=0 && startDateCompare2>0 && endDateCompare1<0 && endDateCompare2<=0) ||
                    (startDateCompare1<0 && startDateCompare2>0 && endDateCompare1<0  && endDateCompare2<=0) ||
                    (startDateCompare1>=0 && startDateCompare2>0 && endDateCompare1<0 && endDateCompare2>0)
            ){
                return "该工作明细与当前设备下其他工作明细发生冲突";
            }

        }
        return null;
    }
}
